package org.jeecg.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.service.ISysPermissionDataRuleService;
import org.jeecg.modules.system.service.ISysPermissionService;
import org.jeecg.modules.system.service.ISysRolePermissionService;
import org.jeecg.modules.system.service.ISysRoleService;
import com.infoclue.modules.km.utils.EmbeddingUtil;
import org.jeecg.modules.system.util.MaxKBUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @Author scott
 */
@RestController
@RequestMapping("/sys/knowledgebase")
@Slf4j
public class SysKnowledgeBaseController {
    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysPermissionDataRuleService sysPermissionDataRuleService;

    @Autowired
    private ISysRolePermissionService sysRolePermissionService;

    @Autowired
    private ISysPermissionService sysPermissionService;

    @Value("${jeecg.maxkb.maxkb_url}")
    private String maxkbUrl;

    @Value("${jeecg.maxkb.maxkb_username}")
    private String maxkbName;

    @Value("${jeecg.maxkb.maxkb_userpass}")
    private String maxkbPass;

    @Value("${jeecg.maxkb.maxkb_userid}")
    private String maxkbId;



    /**
     * 分页列表查询
     * @param role
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<SysRole>> queryPageList(SysRole role,
                                                @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                HttpServletRequest req) {
        role.setRoleType(1);
        Result<IPage<SysRole>> result = new Result<IPage<SysRole>>();
        QueryWrapper<SysRole> queryWrapper = QueryGenerator.initQueryWrapper(role, req.getParameterMap());
        Page<SysRole> page = new Page<SysRole>(pageNo, pageSize);
        IPage<SysRole> pageList = sysRoleService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     *   添加
     * @param role
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<SysRole> add(@RequestBody SysRole role) {
        Result<SysRole> result = new Result<SysRole>();
        try {
            role.setCreateTime(new Date());
            role.setRoleType(1);
            UUID uuid = UUID.randomUUID();
            role.setRoleCode(String.valueOf(uuid));
            sysRoleService.save(role);
            MaxKBUtil.CreateKnowledgeBase(role,maxkbUrl,maxkbId,maxkbName,maxkbPass);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     *  编辑
     * @param role
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public Result<SysRole> edit(@RequestBody SysRole role) {
        Result<SysRole> result = new Result<SysRole>();
        SysRole sysrole = sysRoleService.getById(role.getId());
        if(sysrole==null) {
            result.error500("未找到对应实体");
        }else {
            try {
            String RoleName=sysrole.getRoleName();
            MaxKBUtil.editKnowledgeBase(RoleName,role,maxkbUrl,maxkbName,maxkbPass);
            role.setUpdateTime(new Date());
            boolean ok = sysRoleService.updateById(role);
            //TODO 返回false说明什么？
            if(ok) {
                result.success("修改成功!");
              }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                result.error500("操作失败");
            }
        }
        return result;
    }

    /**
     *   通过id删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestParam(name="id",required=true) String id) throws IOException {
         SysRole role =sysRoleService.selectRoleid(id);
         log.info("===========getRoleName========"+role.getRoleName());
        MaxKBUtil.DeleteKnowledgeBase(role,maxkbUrl,maxkbId,maxkbName,maxkbPass);
        sysRoleService.deleteRole(id);
        return Result.ok("删除知识库成功");
    }

    /**
     *  批量删除
     * @param ids
     * @return
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<SysRole> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        Result<SysRole> result = new Result<SysRole>();
        if(oConvertUtils.isEmpty(ids)) {
            result.error500("未选中知识库！");
        }else {
            sysRoleService.deleteBatchRole(ids.split(","));
            result.success("删除知识库成功!");
        }
        return result;
    }




}
